package sapling.security;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.FilterChainManager;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.factory.BeanInitializationException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * 权限拦截器
 */
public class    AuthShiroFilterFactoryBean extends ShiroFilterFactoryBean {

    @Override
    protected AbstractShiroFilter createInstance() throws Exception {
        SecurityManager securityManager = getSecurityManager();
        if (securityManager == null) {
            throw new BeanInitializationException("securityManager cannot be null");
        }

        if (!(securityManager instanceof WebSecurityManager)) {
            throw new BeanInitializationException("securityManager must be WebSecurityManager");
        }

        FilterChainManager manager = createFilterChainManager();

        PathMatchingFilterChainResolver chainResolver = new PathMatchingFilterChainResolver();
        chainResolver.setFilterChainManager(manager);

        return new AuthShiroFilter((WebSecurityManager) securityManager, chainResolver);
    }

    private final class AuthShiroFilter extends AbstractShiroFilter {

        protected AuthShiroFilter(WebSecurityManager webSecurityManager, FilterChainResolver resolver) {
            setSecurityManager(webSecurityManager);
            if (resolver != null) setFilterChainResolver(resolver);
        }

        @Override
        protected void doFilterInternal(ServletRequest servletRequest, ServletResponse servletResponse,
                                        FilterChain chain) throws ServletException, IOException {
            super.doFilterInternal(servletRequest, servletResponse, chain);
        }

    }


}
